package net.lzzy.spingsecurity.Controller;


import net.lzzy.spingsecurity.entity.Article;
import net.lzzy.spingsecurity.entity.Comment;
import net.lzzy.spingsecurity.service.ArticleService;
import net.lzzy.spingsecurity.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class ClientController{
@Autowired
private ArticleService articleService;
@Autowired
private CommentService commentService;
//访问主页时转到分页的第一页
@GetMapping("/")
public String index(Model model){
        return page(1, model);
        }
//分页显示文章
@GetMapping("/page/{page}")
public String page(@PathVariable("page")int page, Model model){
//分页每页文章数
        int size = 5;
        Page<Article> articles = articleService.pageArticle(page-1, size);
        model.addAttribute("page", page);
        model.addAttribute("totalPage", articles.getTotalPages());
        model.addAttribute("articles", articles.getContent());
        return"client/index";
        }
//文章详情页
@GetMapping("/article/{id}")
public String article(@PathVariable("id")int id, Model model){
        Article article = articleService.findArticleById(id);
        List<Comment> comments = commentService.findCommentByArticleId(id);
        model.addAttribute("article", article);
        model.addAttribute("comments",comments);
        return"client/article";
        }
@PostMapping("/article/{id}/comment")
public String comment(@PathVariable("id")int id,
@RequestParam("author") String author, @RequestParam("content")String
        content){
        commentService.addComment(id, author, content);
        return"redirect:/article/"+id;
        }
        }
